package com.pedro.encoder.input.gl.render.filters;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.pedro.encoder.R;
import com.pedro.encoder.utils.gl.GlUtil;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Random;

/**
 * 呼吸效果滤镜
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public class RespiratoryFilter extends BaseFilterRender{

    private final float[] squareVertexDataFilter = {
            // X, Y, Z, U, V
            -1f, -1f, 0f, 0f, 0f, //bottom left
            1f, -1f, 0f, 1f, 0f, //bottom right
            -1f, 1f, 0f, 0f, 1f, //top left
            1f, 1f, 0f, 1f, 1f, //top right
    };
    private int program = -1;
    private int aPositionHandle = -1;
    private int aTextureHandle = -1;
    private int uMVPMatrixHandle = -1;
    private int uSTMatrixHandle = -1;

    private int uFrequency = -1;
    private int uTime = -1;
    private int uAmplitude = -1;
    private int uCenter = -1;
    private int uRadius = -1;

    private int uSamplerHandle = -1;
    //pram
    private long frameIndex=0;
    private float touchX=0.0f;
    private float touchY=0.5f;
    private  int interval=300;//时间间隔，每多少毫秒出发一次特效，默认200ms
    private  boolean touchRandom=true;

    private long startTime=0;
    //是否水平方向移动
    private boolean left2right=false;
    private boolean right2left=true;
    //水平方向移动完成一次的时长，多少秒
    float period = 5f;

    public RespiratoryFilter(){
        squareVertex = ByteBuffer.allocateDirect(squareVertexDataFilter.length * FLOAT_SIZE_BYTES)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        squareVertex.put(squareVertexDataFilter).position(0);
        Matrix.setIdentityM(MVPMatrix, 0);
        Matrix.setIdentityM(STMatrix, 0);
    }

    public static float nextFloat(final float min, final float max) {
        return min + ((max - min) * new Random().nextFloat());
    }

    /**
     *
     uniform mat4 uMVPMatrix;       // 模型视图投影矩阵
     uniform mat4 uSTMatrix;
     uniform vec2 uCenter;          // 呼吸效果的中心点（归一化的坐标）
     uniform float uRadius;         // 呼吸效果的作用半径
     uniform float uTime;           // 当前时间，控制呼吸节奏
     uniform float uAmplitude;      // 呼吸的幅度
     uniform float uFrequency;      // 呼吸的频率
     * @param context
     */
    @Override
    protected void initGlFilter(Context context) {
        String vertexShader = GlUtil.getStringFromRaw(context, R.raw.respiratory_vertex);
        String fragmentShader =GlUtil.getStringFromRaw(context, R.raw.simple_fragment);
        program = GlUtil.createProgram(vertexShader, fragmentShader);
        aPositionHandle = GLES20.glGetAttribLocation(program, "aPosition");
        aTextureHandle = GLES20.glGetAttribLocation(program, "aTextureCoord");
        uMVPMatrixHandle = GLES20.glGetUniformLocation(program, "uMVPMatrix");
        uSTMatrixHandle = GLES20.glGetUniformLocation(program, "uSTMatrix");

        uTime = GLES20.glGetUniformLocation(program, "uTime");
        uAmplitude = GLES20.glGetUniformLocation(program, "uAmplitude");
        uFrequency = GLES20.glGetUniformLocation(program, "uFrequency");
        uCenter = GLES20.glGetUniformLocation(program, "uCenter");
        uRadius = GLES20.glGetUniformLocation(program, "uRadius");

        uSamplerHandle = GLES20.glGetUniformLocation(program, "uSampler");
        startTime=SystemClock.elapsedRealtime();

    }


    @Override
    protected void drawFilter() {
        GLES20.glUseProgram(program);

        squareVertex.position(SQUARE_VERTEX_DATA_POS_OFFSET);
        GLES20.glVertexAttribPointer(aPositionHandle, 3, GLES20.GL_FLOAT, false,
                SQUARE_VERTEX_DATA_STRIDE_BYTES, squareVertex);
        GLES20.glEnableVertexAttribArray(aPositionHandle);

        squareVertex.position(SQUARE_VERTEX_DATA_UV_OFFSET);
        GLES20.glVertexAttribPointer(aTextureHandle, 2, GLES20.GL_FLOAT, false,
                SQUARE_VERTEX_DATA_STRIDE_BYTES, squareVertex);
        GLES20.glEnableVertexAttribArray(aTextureHandle);

        GLES20.glUniformMatrix4fv(uMVPMatrixHandle, 1, false, MVPMatrix, 0);
        GLES20.glUniformMatrix4fv(uSTMatrixHandle, 1, false, STMatrix, 0);

        GLES20.glActiveTexture(GLES20.GL_TEXTURE4);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, previousTexId);
        GLES20.glUniform1i(uSamplerHandle, 4);
        //
        if (SystemClock.elapsedRealtime()-startTime>interval){
            frameIndex+=1;
            if (touchRandom){
                float x= nextFloat(0.0f,1.0f);
                touchX=getWidth()*x;
                float y=nextFloat(0.0f,1.0f);;
                touchY=getHeight()*y;
            }
            startTime=SystemClock.elapsedRealtime();
        }
        float time =frameIndex*1.0f%(150 / 120f);
        GLES20.glUniform1f(uTime, time);
        GLES20.glUniform2f(uCenter, touchX/getWidth(),touchY/getHeight());
        GLES20.glUniform1f(uRadius, 0.5f);
        GLES20.glUniform1f(uFrequency, 1.0f);
        GLES20.glUniform1f(uAmplitude, 0.5f);

        if (left2right||right2left){
            // 获取当前时间
            long currentTime = System.currentTimeMillis();
            // 周期
            float normalizedTime = (currentTime % (long)(period*1000)) / 1000.0f;  // [0, period] 归一化
            // 将归一化的时间转换为中心的 x 坐标
            float tornadoCenterX=0;
            if (left2right){
                tornadoCenterX= normalizedTime / period;
            }else{
                tornadoCenterX = 1.0f - (normalizedTime / period);
            }

            GLES20.glUniform2f(uCenter, tornadoCenterX, touchY);
        }


        GLES20.glActiveTexture(GLES20.GL_TEXTURE4);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, previousTexId);

    }

    @Override
    public void release() {
        GLES20.glDeleteProgram(program);
    }
}
